package com.tz.online.listener;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.tz.online.book.service.IBookService;
import com.tz.online.entity.Category;
import com.tz.online.util.BeanFactory;

/**
 * Application Lifecycle Listener implementation class LoadCategoryListener
 *
 */
@WebListener
public class LoadCategoryListener implements ServletContextListener {
	
	private IBookService bookService = (IBookService) BeanFactory.getBean("bookService");

    /**
     * Default constructor. 
     */
    public LoadCategoryListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent sce)  { 
    	//移除KEY
    	ServletContext cxt = sce.getServletContext();
    	cxt.removeAttribute("ALL_CATE");
    	System.out.println("--移除 ALL_CATE KEY成功...");
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent sce)  { 
    	//加载所有的产品分类
    	List<Category> categories = bookService.getAllCategories();
    	//绑定到应用范围
    	ServletContext cxt = sce.getServletContext();
    	//
    	cxt.setAttribute("ALL_CATE", categories);
    	//
    	System.out.println("--- 加载分类成功，并绑定到应用范围，KEY：ALL_CATE");
    }
	
}
